﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Threading;
using HandyControl.Tools;
using RemoteTool.Business.Tools;
using RemoteTool.Business.Tools.Extension;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace RemoteTool.Data
{
    public class ConfigManager : ViewModelBase
    {
        private string sysConfigJsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Configs\SystemConfig.json");

        private List<string> todeskPaths = new List<string>() {
            @"C:\Program Files (x86)\ToDesk",
            @"D:\Program Files (x86)\ToDesk",
            @"D:\Program Files\ToDesk",
        };
        private List<string> oraySunPaths = new List<string>() {
            @"C:\Program Files (x86)\Oray\SunLogin\SunloginClient",
            @"D:\Program Files (x86)\Oray\SunLogin\SunloginClient",
            @"D:\Program Files\SunLogin",
        };

        private SystemConfig _sysConfig;
        public SystemConfig SysConfig { get => _sysConfig; set { _sysConfig = value; RaisePropertyChanged(nameof(SysConfig)); } }

        private object operatLocer = new object();

        public ConfigManager()
        {
            SysConfig = sysConfigJsonPath.FromJsonFile<SystemConfig>();

            Task.Run(() =>
            {
                if (string.IsNullOrEmpty(SysConfig.ToDeskExePath))
                {
                    foreach (var item in todeskPaths)
                    {
                        if (FileHelper.IsExistDirectory(item))
                        {
                            DispatcherHelper.CheckBeginInvokeOnUI(() => { SysConfig.ToDeskExePath = item; });
                        }
                    }
                }

                if (string.IsNullOrEmpty(SysConfig.OraySunExePath))
                {
                    foreach (var item in oraySunPaths)
                    {
                        if (FileHelper.IsExistDirectory(item))
                        {
                            DispatcherHelper.CheckBeginInvokeOnUI(() => { SysConfig.OraySunExePath = item; });
                        }
                    }
                }
               
            });
        }


        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="saveBackup">是否保存备份</param>
        public void Save(bool saveBackup = false)
        {
            Task.Run(() =>
            {
                lock (operatLocer)
                {
                    SysConfig.ToJsonFile(sysConfigJsonPath);
                }
            });
        }
    }
}
